package com.yhx.security.gfoBank.file;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yhx.testDemo.FastJsonUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 数据转换工具类
 *
 * @author zhangxiaoli5
 * @create 2018-07-06 10:24
 **/
public class DataConvertUtils {

    
    public static <T>  List<T> jsonToList(String jsonStr , Class<T> clazz){
        try{
            List<T> list = FastJsonUtils.toList(jsonStr, clazz);
            return list;
        }catch (Exception e){

        }
        return new ArrayList<T>();
    }

    public static <T> HashMap<String,T> jsonToHashMap(String json, Class<T> clazz){
        if(StringUtils.isBlank(json)){
            return new HashMap<String, T>();
        }
        try {
            HashMap<String, Object> tmpMap = FastJsonUtils.toBean(json,HashMap.class);
            HashMap<String, T> resultMap = new HashMap<String, T>();
            for(String key : tmpMap.keySet()){
                String str = JSONObject.toJSONString(tmpMap.get(key));
                resultMap.put(key, FastJsonUtils.toBean(str, clazz));
            }
            return  resultMap;
        }catch (Exception e){
        }
        return new HashMap<>();
    }

    public static <T> HashMap<Integer,T> jsonToHashMapWithIntegerKey(String json, Class<T> clazz){
        try {
            HashMap<String, Object> tmpMap = FastJsonUtils.toBean(json,HashMap.class);
            HashMap<Integer, T> resultMap = new HashMap<>();
            for(String key : tmpMap.keySet()){
                String str = JSONObject.toJSONString(tmpMap.get(key));
                resultMap.put(Integer.parseInt(key), FastJsonUtils.toBean(str, clazz));
            }
            return  resultMap;
        }catch (Exception e){
        }
        return new HashMap<>();
    }

    public static <T> HashMap<String,  List<T>> jsonToMapWithListValue(String json, Class<T> clazz){
        HashMap<String,  List<T>> maps = new HashMap<String, List<T>>();
        try {
            maps = FastJsonUtils.toBean(json,HashMap.class);
            for(String key : maps.keySet()){
                List<T> list = JSON.parseArray(JSON.parseObject(json).getString(key), clazz);
                maps.put(key,list);
            }
        }catch (Exception e){
        }
        return maps;
    }

    public static <T> T mapToObject(Map<String, Object> map, T t) {
        Class beanClass = t.getClass();
        String[] declaredFieldsName = getDeclaredFieldsName(beanClass);
        for (String k : map.keySet()) {
            Object v = map.get(k);
            if (ArrayUtils.contains(declaredFieldsName, k)) {
                try {
                    Field field = beanClass.getDeclaredField(k);
                    field.setAccessible(true);
                    field.set(t, v);
                } catch (Exception e) {
                }
            }
        }
        return t;
    }

    public static <T> T mapToObject(Map<String, String> map, Class<T> beanClass) {
        if(beanClass==null){
            return null;
        }
        T instance = null;
        try {
            instance = beanClass.newInstance();

            if(map==null || map.isEmpty()){
                return instance;
            }
            Field[] fields = beanClass.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                String stringValue = map.get(fieldName);
                if(StringUtils.isBlank(stringValue)){
                    continue;
                }
                Class<?> fieldType = field.getType();
                Object fieldValue = stringToObject(stringValue,fieldType);
                if(fieldValue==null){
                    continue;
                }
                String methodName = "set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
                Method method = beanClass.getMethod(methodName, fieldType);

                method.invoke(instance,fieldValue);
            }
        } catch (Exception e) {
        }
        return instance;
    }

    private static Object stringToObject(String str,Class<?> type) {
        if(StringUtils.isBlank(str) || type==null){
            return null;
        }
        Object value = null;
        try {
            if (type == int.class || type == Integer.class) {
                value = Integer.parseInt(str);
            } else if (type == float.class || type == Float.class) {
                value = Float.parseFloat(str);
            } else if (type == double.class || type == Double.class) {
                value = Double.parseDouble(str);
            } else if (type == boolean.class || type == Boolean.class) {
                // 只有当 str 等于 'true' 返回 true
                value = Boolean.parseBoolean(str);
            } else if (type == String.class) {
                value = str;
            } else if (type == Date.class) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                value = format.parse(str);
            } else {
            }
        }catch (Exception e){
        }
        return value;
    }


    public static <T> T strMapToObject(Map<String, String> map, T t) {
        Class beanClass = t.getClass();
        String[] declaredFieldsName = getDeclaredFieldsName(beanClass);
        for (String k : map.keySet()) {
            String v = map.get(k);
            if (ArrayUtils.contains(declaredFieldsName, k)) {
                try {
                    Field field = beanClass.getDeclaredField(k);
                    field.setAccessible(true);
                    field.set(t, v);
                } catch (Exception e) {
                }
            }
        }
        return t;
    }

    public static String[] getDeclaredFieldsName(Class beanClass) {
        Field[] fields = beanClass.getDeclaredFields();
        int size = fields.length;
        String[] fieldsName = new String[size];
        for (int i = 0; i < size; i++) {
            fieldsName[i] = fields[i].getName();
        }
        return fieldsName;
    }

    public static HashMap<String, Object> javaBean2Map(Object javaBean){
        HashMap<String, Object> map = new HashMap<>();
        try {
            Method[] methods = javaBean.getClass().getMethods(); // 获取所有方法
            for (Method method : methods) {
                if (method.getName().startsWith("get")) {
                    String field = method.getName(); // 拼接属性名
                    field = field.substring(field.indexOf("get") + 3);
                    field = field.toLowerCase().charAt(0) + field.substring(1);
                    if("class".equalsIgnoreCase(field)){
                        continue;
                    }
                    Object value = method.invoke(javaBean, (Object[]) null); // 执行方法
                    map.put(field, value);
                }
            }
        }catch (Exception e){
        }

        return map;
    }
    /**
     * 计算百分比，取整(两位数)
     * @param count 已使用量
     * @param countLimit 总量 ，为-1表示无限制
     * @return
     */
    public static Integer getResidualPercentage(Integer count, Integer countLimit) {
        if (countLimit == null || countLimit == 0) {
            return 0;
        }
        if (countLimit == -1 || count == null) {
            return 100;
        }
        if (count >= countLimit) {
            return 0;
        }
        try {
            double percent = ((double) (countLimit - count) / countLimit) * 100;
            if (percent > 0 && percent < 1) {//余量不足1%的时候，默认返回1%
                return 1;
            }
            String percentStr = percent + "";
            return Integer.parseInt(percentStr.split("\\.")[0]);
        } catch (Exception e) {
        }
        return 0;

    }
}
